<template>
  <div class="form-page">
    <el-form
      ref="dataForm"
      element-loading-text="正在导入试题。。。"
      :model="dataForm"
      :inline="true"
      label-width="10em"
      :rules="dataFormRule"
      class="data-form"
    >
      <div
        class="form-item xy-start al-str"
        style="height:500px"
      >
        <div class="title">导入信息</div>
        <div
          class="yx-start al-start data"
          align="center"
          style="display"
        >
          <div class="childrenDiv">
            <el-form-item
              label="学科"
              prop="classificationId"
            >
              <el-cascader
                ref="classification"
                :key="zeroOne"
                v-model="dataForm.classificationId"
                :props="classificationProps"
                :show-all-levels="false"
                filterable
                clearable
                @change="changeClassification"
              ></el-cascader>
            </el-form-item>
          </div>
          <div class="childrenDiv">
            <el-radio-group
              v-model="radio1"
              @change="choicePaperOrChapters"
            >
              <el-radio
                label="1"
                border
              >导入到试卷</el-radio>
              <el-radio
                label="2"
                border
              >导入到章节</el-radio>
            </el-radio-group>
          </div>
          <div class="childrenDiv">
            <div v-if="isPaper">
              <div>
                <el-form-item
                  label="试卷类型"
                  prop="paperType"
                >
                  <el-select
                    v-model="dataForm.paperType"
                    clearable
                    placeholder="请选择"
                    @clear="cleanPaper"
                    @change="
                                            selectPaper(dataForm.paperType)
                                        "
                  >
                    <el-option
                      v-for="item in paperTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div>
                <el-form-item
                  label="试卷"
                  prop="paperId"
                >
                  <el-select
                    v-model="dataForm.paperId"
                    clearable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in paperOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>
            <div v-else>
              <el-form-item
                label="章节"
                prop="chapterId"
              >
                <el-cascader
                  ref="chapter"
                  :key="zeroTwo"
                  v-model="dataForm.chapterId"
                  :props="chapterProps"
                  :show-all-levels="false"
                  filterable
                  clearable
                ></el-cascader>
              </el-form-item>
            </div>
          </div>
        </div>

        <div class="upload">
          <el-upload
            ref="upload"
            class="upload-demo"
            action="/api/exam/question/add-source-collect"
            :headers="headerObj"
            :data="dataForm"
            :multiple="false"
            accept=".doc,.docx"
            :limit="1"
            :on-progress="uploading"
            :on-success="successUpload"
            :on-error="failUpload"
            :auto-upload="false"
          >
            <el-button type="primary">上传<i class="el-icon-upload el-icon--right"></i></el-button>
            <span
              slot="tip"
              class="el-upload__tip"
              style="margin-left:5px"
            >只能上传doc和docx文件</span>
          </el-upload>
        </div>

        <div class="import">
          <el-button
            style="margin-left: 10px;"
            size="small"
            type="success"
            @click="submitForm()"
          >导入
          </el-button>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import { FormPage } from "@/layout/mixin/iVue.js";
import { mapState } from "vuex";
import {
  fetchCategoryChildren,
  fetchCategoryFirstStage,
  fetchClassificationChildren,
  fetchClassificationFirst
} from "@/api/course";
import {
  fetchChapterFirstStage,
  fetchChapterChildren,
  fetchQuestionType,
  fetchPaper
} from "@/api/exam";

var options = {
  lock: true,
  text: "正在导入试题",
  spinner: "el-icon-loading",
  background: "rgba(0, 0, 0, 0.7)"
};

export default {
  name: "ImportQuestion",
  mixins: [FormPage],
  data () {
    return {
      headerObj: { dt: "admin" },
      zeroOne: 0,
      zeroTwo: 0,
      uploadText: "",
      radio1: "1",
      category: null,
      classId: null,
      paperTypeOptions: [
        {
          value: "chapterText",
          label: "章节测试"
        },
        {
          value: "finalExam",
          label: "期末考试"
        },
        {
          value: "normalExam",
          label: "普通考试"
        }
      ],
      paperQueryData: {
        paperType: null,
        pageSize: 999,
        currentPage: 1,
        classificationId: null
      },
      dataForm: {
        schoolLevel: null,
        classificationId: null,
        paperId: null,
        chapterId: null,

      },
      loading: false,
      classificationList: [],
      paperList: [],
      chapterList: [],
      isPaper: true,
      fullscreenLoading: false,
      classificationProps: {
        lazy: true,
        checkStrictly: true,
        emitPath: false,
        lazyLoad: this.fetchClassification
      },
      chapterProps: {
        lazy: true,
        checkStrictly: true,
        lazyLoad: this.fetchChapter
      },
      paperOptions: [],
      dataFormRule: {
        classificationId: [
          { required: true, message: "请选择！", trigger: "change" }
        ],
        paperId: [
          { required: true, message: "请选择！", trigger: "change" }
        ],
        paperType: [
          { required: true, message: "请选择！", trigger: "change" }
        ],
        chapterId: [
          { required: true, message: "请选择！", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    ...mapState({
      status: state => state.status.questionFirstType
    })
  },
  watch: {
    actionSearch (val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    changeSchoolLevel () {
      this.dataForm.classificationId = [];
      ++this.zeroOne;
    },
    changeClassification (data) {
      this.classId = this.$refs.classification.getCheckedNodes()[0].value;
      this.dataForm.chapterId = [];
      ++this.zeroTwo;
    },
    fetchChapter (node, resolve) {
      const { level } = node;
      if (this.classId !== null) {
        if (!node.data) {
          fetchChapterFirstStage({
            classificationId: this.classId
          }).then(res => {
            const nodes = Array.from(res).map(item => {
              return {
                value: item.id,
                label: `${item.name}`,
                leaf:
                  level >= (item.children.length > 0 ? 1 : 0)
              };
            });
            resolve(nodes);
          });
        } else {
          fetchChapterChildren({ id: node.data.value }).then(res => {
            const nodes = Array.from(res).map(item => {
              return {
                value: item.id,
                label: `${item.name}`,
                leaf:
                  level >=
                  (item.children.length > 0 ? level + 1 : 0)
              };
            });
            resolve(nodes);
          });
        }
      }
    },
    fetchClassification (node, resolve) {
      const { level } = node;
      if (!node.data) {
        fetchClassificationFirst().then(res => {
          const nodes = Array.from(res).map(item => {
            return {
              value: item.id,
              label: `${item.name}`,
              leaf: level >= (item.children.length > 0 ? 1 : 0)
            };
          });
          resolve(nodes);
        });
      } else {
        fetchClassificationChildren({ id: node.data.value }).then(
          res => {
            const nodes = Array.from(res).map(item => {
              return {
                value: item.id,
                label: `${item.name}`,
                leaf:
                  level >=
                  (item.children.length > 0 ? level + 1 : 0)
              };
            });
            resolve(nodes);
          }
        );
      }
    },
    choicePaperOrChapters (data) {
      if (data === "1") {
        this.isPaper = true;
      } else if (data === "2") {
        this.isPaper = false;
      }
    },
    submitForm () {
      this.dataForm.classificationId = this.$refs.classification.getCheckedNodes()[0].value;
      if (this.isPaper) {
        this.dataForm.chapterId = "";
      } else {
        this.dataForm.chapterId = this.$refs.chapter.getCheckedNodes()[0].value;
        this.dataForm.paperId = "";
      }
      this.$refs.upload.submit();
    },
    uploading () {
      this.$loading(options);
    },
    successUpload (response) {
      this.$loading().close();
      let msg = "";
      const res = response.data;
      switch (res.res) {
        case "success":
          msg =
            "导入成功！一共" +
            res.count +
            "道，成功" +
            res.okNum +
            "道，修改" +
            res.existNum +
            "道";
          break;
        case "fail":
          msg =
            "导入部分试题失败！一共" +
            res.count +
            "道，成功" +
            res.okNum +
            "道，修改" +
            res.existNum +
            "道，失败" +
            res.noNum +
            "道";
          break;
        case "exist":
          msg =
            "内容完全重复！一共" +
            res.count +
            "道，修改" +
            res.existNum +
            "道";
          break;
        default:
          msg = "导入出错";
          break;
      }
      this.$alert(msg, "导入结果", {
        confirmButtonText: "确定"
      });
    },
    failUpload () {
      this.$loading().close();
      this.$message({
        showClose: true,
        message: "上传失败",
        type: "error"
      });
    },
    selectPaper (data) {
      this.cleanPaper();
      this.paperOptions = [];
      this.paperQueryData.paperType = data;
      this.paperQueryData.classificationId = this.$refs.classification.getCheckedNodes()[0].value;
      fetchPaper(this.paperQueryData).then(res => {
        console.log("res", res);
        for (let i = 0; i < res.records.length; i++) {
          this.paperOptions.push({
            value: res.records[i].id,
            label: res.records[i].name
          });
        }
      });
      console.log(" this.paperOptions", this.paperOptions);
    },
    cleanPaper () {
      delete this.dataForm.paperId;
    }
  }
};
</script>

<style lang="scss" scoped>
.form-page .form-item .data {
  display: flex;
}

.childrenDiv {
  margin-top: 6px;
  height: 55px;
}
.el-form-item__label {
  width: 6em;
}

.upload {
  margin-top: 60px;
  margin-left: 120px;
}
.import {
  margin-top: 30px;
  margin-left: 270px;
}
.el-radio-group {
  display: inline-block;
  line-height: 1;
  vertical-align: middle;
  font-size: 0;
  margin-left: 50px;
}
</style>
